

#include <string.h>
#include "bit_mark.h"

uint8_t bit_mark_init(BIT_MARK_STRUCT* bit_mark,
					uint8_t* buffer, uint8_t buffer_len, uint16_t bit_mark_count)	//bit_mark_count 0~0xffff
{
	if((bit_mark == 0)||(buffer == 0)||(buffer_len == 0)
		||(bit_mark_count+1 > buffer_len*8)){
		return 0;
	}

	bit_mark->bit_mark_buffer = buffer;
	bit_mark->bit_mark_count = bit_mark_count;

	memset(buffer, 0, buffer_len);

	return 1;
}

uint8_t bit_mark_set(BIT_MARK_STRUCT* bit_mark, uint16_t bits)	//bits 0~0xffff
{
	uint8_t* p;
    uint8_t mark;

    if(bits <= bit_mark->bit_mark_count){
		p = &(bit_mark->bit_mark_buffer[bits/8]);
		mark = 1<<(bits%8);
		/***critical section***/
        (*p) |= mark;
		/**********************/
        return 1;
    }
    else{
        return 0;
    }
}

uint8_t bit_mark_reset(BIT_MARK_STRUCT* bit_mark, uint16_t bits)
{
	uint8_t* p;
    uint8_t mark;

    if(bits <= bit_mark->bit_mark_count){
		p = &(bit_mark->bit_mark_buffer[bits/8]);
		mark = 1<<(bits%8);
		mark = ~mark;
		/***critical section***/
		(*p) &= mark;
		/**********************/
        return 1;
    }
    else{
        return 0;
    }
}

uint8_t bit_mark_get(BIT_MARK_STRUCT* bit_mark, uint16_t bits)
{
	uint8_t* p;
    uint8_t mark;

    if(bits <= bit_mark->bit_mark_count){
		p = &(bit_mark->bit_mark_buffer[bits/8]);
		mark = 1<<(bits%8);
        if(((*p)&mark) != 0){
            return 1;
        }
        else{
            return 0;
        }
    }
    else{
        return 0xff;
    }
}

void bit_mark_reset_all(BIT_MARK_STRUCT* bit_mark)
{
	memset(bit_mark->bit_mark_buffer, 0,
			((bit_mark->bit_mark_count)/8)+1);
}

uint8_t bit_mark_check_all_reset(BIT_MARK_STRUCT* bit_mark)
{
	uint8_t i;
	for(i = 0; i <= ((bit_mark->bit_mark_count)/8); i++){
        if(bit_mark->bit_mark_buffer[i] != 0){
            return 0;
        }
	}
	return 1;
}

/**
//e.g.
void print_bit_mark(BIT_MARK_STRUCT* bit_mark)
{
	uint8_t i;
	for(i = 0; i <= bit_mark->bit_mark_count; i++){
		printf("%d ", bit_mark_get(bit_mark, i));
	}
	printf("\r\n");
}

uint8_t bit_mark_test_buffer[5];
BIT_MARK_STRUCT bit_mark_test;
void bit_mark_test_f(void)
{
	bit_mark_init(&bit_mark_test, bit_mark_test_buffer, 5, 25);
	print_bit_mark(&bit_mark_test);

	bit_mark_set(&bit_mark_test, 5);
	bit_mark_set(&bit_mark_test, 6);
	print_bit_mark(&bit_mark_test);

	bit_mark_set(&bit_mark_test, 12);
	bit_mark_set(&bit_mark_test, 20);
	print_bit_mark(&bit_mark_test);

	bit_mark_reset(&bit_mark_test, 12);
	bit_mark_reset(&bit_mark_test, 20);
	print_bit_mark(&bit_mark_test);

	printf("bit_mark_check_all_reset %d\r\n", bit_mark_check_all_reset(&bit_mark_test));

	bit_mark_reset_all(&bit_mark_test);
	print_bit_mark(&bit_mark_test);

	printf("bit_mark_check_all_reset %d\r\n", bit_mark_check_all_reset(&bit_mark_test));
}
**/
